#include"target_flash.h"
#include"ch32f103_flash.h"
#define using_ch32flash
char *mem_xml_get(void)
{
    char*mem_xml;
    unsigned int offset=0,ret , i,len;
    len = sizeof(TargetFlash_t)/sizeof(TargetFlash);
    mem_xml = mymalloc(len*96 +32);
    if(mem_xml)
    {
        memset(mem_xml,0,len*96 +32);
        ret = sprintf(mem_xml,"l<memory-map>\n");
        offset = ret;
        for(i = 0; i < len; i++)
        {
            if(TargetFlash_t[i].Type != RAM_Type)
            {
                ret = sprintf(mem_xml + offset,"<memory type=\"flash\" start=\"0x%08x\" length=\"0x%x\">\n",
                    TargetFlash_t[i].Addr,TargetFlash_t[i].Length);
                offset += ret;
                ret = sprintf(mem_xml + offset,"<property name=\"blocksize\">0x%x</property>\n",TargetFlash_t[i].BlockSize);
                offset += ret;
                ret = sprintf(mem_xml + offset,"</memory>\n");
                offset += ret;
            }
            else
            {
                ret = sprintf(mem_xml + offset,"<memory type=\"ram\" start=\"0x%08x\" length=\"0x%08x\"/>\n",
                    TargetFlash_t[i].Addr,TargetFlash_t[i].Length);
                offset += ret;
            }
        }
        ret = sprintf(mem_xml + offset,"</memory-map>\n");
        offset += ret;
    }
    return mem_xml;
}
unsigned int IsFlash(unsigned int addr,unsigned int len)
{
    unsigned int ret = 0,i,Saddr,Eaddr;
    len = sizeof(TargetFlash_t)/sizeof(TargetFlash);
    for(i = 0; i < len; i++)
    {
        Saddr = TargetFlash_t[i].Addr;
        Eaddr = TargetFlash_t[i].Addr + TargetFlash_t[i].Length - 1;
        if((addr >= Saddr) && (addr <= Eaddr))
        {
            if(TargetFlash_t[i].Type == RAM_Type)
            {
                ret = 0;
            }
            else
            {
                ret = 1;
            }
        }
    }
    return ret;
}

unsigned int TargetFlashErase(unsigned int addr,unsigned int length)
{
    unsigned int ret;
#ifdef using_ch32flash
    ret = ch32_FlashErase(addr,length);
#endif
    return ret;
}
unsigned int TargetFlashProgram(unsigned int addr,char*buf,unsigned int len)
{
    unsigned int ret;
#ifdef using_ch32flash
    ret = TargetFlashWrite(addr,buf,len);
#endif
    return ret;
}
unsigned int TargetFlashWrite(unsigned int addr,char*buf,unsigned int len)
{
    unsigned int ret;
#ifdef using_ch32flash
    ret = ch32_FlashProgram(addr,buf,len);
#endif
    return ret;
}